#pragma once

#include <BinXCAFDrivers.hxx>
#include <STEPCAFControl_Reader.hxx>
#include <TDocStd_Application.hxx>
#include <TDocStd_Document.hxx>

#include "DisplayScene.h"
#include "Viewer.h"

namespace
{
	Handle(TDocStd_Document) ReadStepWithMeta(const std::string& filename)
	{
		STEPCAFControl_Reader Reader;

		// Create XDE document.
		Handle(TDocStd_Application) app = new TDocStd_Application;
		BinXCAFDrivers::DefineFormat(app);
		Handle(TDocStd_Document) doc;
		app->NewDocument("BinXCAF", doc);

		// Read CAD and associated data from file
		try
		{
			IFSelect_ReturnStatus outcome = Reader.ReadFile(filename.c_str());
			//
			if (outcome != IFSelect_RetDone)
			{
				app->Close(doc);
				return nullptr;
			}

			if (!Reader.Transfer(doc))
			{
				app->Close(doc);
				return nullptr;
			}
		}
		catch (...)
		{
			app->Close(doc);
			return nullptr;
		}

		return doc;
	}
}

void lesson12_main(const std::string& strFileName)
{
	Viewer vout(50, 50, 500, 500);

	Handle(TDocStd_Document) doc = ::ReadStepWithMeta(strFileName);
	//
	if (doc.IsNull())
	{
		std::cout << "Failed to read STEP model from file " << strFileName << std::endl;
		return;
	}

	DisplayScene cmd(doc, vout.GetContext());
	if (!cmd.Execute())
	{
		std::cout << "Failed to visualize CAD model with `DisplayScene` command." << std::endl;
		return;
	}

	vout.StartMessageLoop();
}
